<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item to="/">首页</el-breadcrumb-item>
      <el-breadcrumb-item to="/admin/product/spumanage"
        >商品管理</el-breadcrumb-item
      >
      <el-breadcrumb-item to="/admin/product/category"
        >商品类别</el-breadcrumb-item
      >
      <el-breadcrumb-item>修改商品类别</el-breadcrumb-item>
    </el-breadcrumb>

    <el-divider></el-divider>

    <div class="box">
      <el-row>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <h3 style="line-height: 32px">
              <i class="el-icon-edit"></i> &nbsp; 内容信息
            </h3>
          </div>
        </el-col>
      </el-row>
      <div class="divider"></div>
      <el-row>
        <el-col :span="12">
          <el-form
            :model="ruleForm"
            :rules="rules"
            ref="ruleForm"
            label-width="180px"
            class="demo-ruleForm"
          >
            <el-form-item label="上级类别" prop="parentId">
              <el-cascader
                style="width: 100%"
                placeholder="点击选择上级类别，否则默认一级类别"
                size="small"
                :props="props"
                v-model="ruleForm.parentId"
              ></el-cascader>
            </el-form-item>
            <el-form-item label="类别名称" prop="name">
              <el-input size="small" v-model="ruleForm.name"></el-input>
            </el-form-item>
            <el-form-item label="排序" prop="sort">
              <el-input size="small" v-model="ruleForm.sort"></el-input
              >（排序值越大越靠前）
            </el-form-item>
            <el-form-item label="是否启用" prop="enable">
              <el-switch
                :active-value="1"
                :inactive-value="0"
                v-model="ruleForm.enable"
                active-color="#1aa"
                inactive-color="#aaa"
              ></el-switch>
            </el-form-item>
            <el-form-item label="是否在导航栏中显示" prop="isDisplay">
              <el-switch
                :active-value="1"
                :inactive-value="0"
                v-model="ruleForm.display"
                active-color="#1aa"
                inactive-color="#aaa"
              ></el-switch>
            </el-form-item>
            <el-form-item label="类别图标" prop="icon">
              <input type="hidden" v-model="ruleForm.icon" />
              <el-upload
                class="avatar-uploader"
                :show-file-list="false"
                name="file"
                :data="{ categoryNamePinyin: ruleForm.name }"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :action="`${BASEURL.UPLOAD_BASEURL}/upload/category-icon`"
              >
                <img v-if="ruleForm.icon" :src="ruleForm.icon" class="avatar" style="width: 130px; height: auto;" />
              </el-upload>
            </el-form-item>
            <el-form-item label="关键词" prop="keywords">
              <el-input size="small" v-model="ruleForm.keywords"></el-input>
            </el-form-item>
            <div class="divider"></div>
            <el-button @click="$router.go(-1)">返回</el-button>
            <el-button type="primary" @click="submitForm('ruleForm')"
              >确认</el-button
            >
          </el-form>
        </el-col>
      </el-row>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      value: "",
      ruleForm: {
        parentId: [0], //默认父类别为根类别
      },
      rules: {
        name: [{ required: true, message: "请输入类别名称", trigger: "blur" }],
        sort: [{ required: true, message: "请输入排序序号", trigger: "blur" }],
        keywords: [
          {
            required: true,
            message: "请输入关键词（多个关键词以英文逗号分隔）",
            trigger: "blur",
          },
        ],
      },
      props: {
        lazy: true, // 懒加载
        checkStrictly: true, // 设置为true，可以选择中间类别
        lazyLoad: (node, resolve) => {
          /** 定义懒加载方式 */
          console.log("选择的当前节点：", node);
          let parentId = 0;
          if (!node.root) {
            parentId = node.data.value;
          }
          this.categoryApi
            .queryByParent({ parentId: parentId })
            .then((res) => {
              console.log("加载子类别：", res);
              if (res.data.state == 200) {
                // 整理数据结构, 返回类别数组 [{label:'类别名', value:'类别id'}...]
                let nodes = [];
                res.data.data.forEach((item) => {
                  nodes.push({
                    label: item.name,
                    value: item.id,
                    leaf: item.isParent != 1,
                  });
                });
                resolve(nodes);
              } else {
                this.$alert(res.data.message, "提示");
              }
            });
        },
      },
    };
  },
  methods: {
    handleAvatarSuccess(res, file) {
      console.log(res);
      this.ruleForm.icon = res.data.url
    },

    beforeAvatarUpload(file) {
      const isJPGPNG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isJPGPNG) {
        this.$message.error("上传图片只能是 JPG/PNG 格式!");
      }
      if (!isLt5M) {
        this.$message.error("上传头像图片大小不能超过 5MB!");
      }
      return isJPGPNG && isLt5M;
    },

    /** 提交表单 */
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log(this.ruleForm);
          // 由于cascader组件返回的parentId为层级数组，所以重置表单中parentId与depth字段
          let parentIds = this.ruleForm.parentId;
          this.ruleForm.parentId = parentIds[parentIds.length - 1];
          this.ruleForm.depth = parentIds.length;
          // 新增类别
          this.categoryApi.update(this.ruleForm).then((res) => {
            console.log("更新类别", res);
            if (res.data.state == 200) {
              this.$message({
                showClose: true,
                message: "恭喜你，类别更新成功",
                type: "success",
              });
              // 重建缓存后 回首页
              return this.categoryApi.rebuildCache()
            } else {
              this.$alert(res.data.message, "提示");
            }
          }).then(res=>{
            console.log("重建缓存：" + res)
            this.$router.push("/admin/product/category");
          })
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },

  /** 页面加载完毕执行 */
  mounted() {
    // 加载当前选中的类别信息， 回填数据
    let categoryId = this.$route.query.id;
    this.categoryApi.queryById(categoryId).then((res) => {
      console.log("根据ID查询类别详情：", res);
      this.ruleForm = res.data.data;
    });
  },
};
</script>
